package com.huang.security.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.entity.OauthClient;
import com.huang.enums.PasswordEncoderTypeEnum;
import com.huang.service.OauthClientService;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 自定义 配置客户端的 资源、密钥等信息
 *
 * @author han
 * @since 2022-02-14 10:35:54
 */
@Service
public class CustomClientDetailsService implements ClientDetailsService {

    @Resource
    private OauthClientService oauthClientService;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        if (StrUtil.isBlank(clientId)) {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
        QueryWrapper<OauthClient> query =  new QueryWrapper<>();
        query.lambda().eq(OauthClient::getClientId, clientId);
        OauthClient client = oauthClientService.getOne(query);
        if (null != client) {
            BaseClientDetails clientDetails = new BaseClientDetails(
                    client.getClientId(),
                    client.getResourceIds(),
                    client.getScope(),
                    client.getAuthorizedGrantTypes(),
                    client.getAuthorities(),
                    client.getWebServerRedirectUri()
            );
            // 设置客户端的密码加密方式
            clientDetails.setClientSecret(PasswordEncoderTypeEnum.NOOP.getPrefix() + client.getClientSecret());
            clientDetails.setAccessTokenValiditySeconds(client.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(client.getRefreshTokenValidity());
            return clientDetails;
        }
        throw new NoSuchClientException("Not found client with requested id: " + clientId);
    }
}
